package com.qingfeng.controller.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.qingfeng.business.biz.file.IRemoteFileService;
import com.qingfeng.business.vo.file.RemoteFileInfo;
import com.qingfeng.common.dto.ResultDTO;
import com.qingfeng.constant.enums.ErrorMessages;
import com.qingfeng.constant.enums.SuccessMessage;
import com.qingfeng.controller.common.BaseController;
import com.qingfeng.exception.BusinessException;
import com.qingfeng.utils.LogUtil;

@Controller
@RequestMapping("fileUtil")
public class FileUtilController extends BaseController {
	@Autowired
	IRemoteFileService remoteFileService;

	/**
	 * 上传图片 需要压缩（单个）
	 * 
	 * @param request
	 * @param response
	 * @param height
	 * @param width
	 */
	@RequestMapping("/uploadImageFile.jpeg")
	public void uploadImageFile(HttpServletRequest request, HttpServletResponse response, Integer height,
			Integer width,boolean flag) {
		try {
		    if(height ==0){
		        height =null;
		    }
			ResultDTO<RemoteFileInfo> resultDTO = remoteFileService.saveUploadImageFile(request, height, width,flag);
			if (resultDTO.isSuccess()) {
				this.sendJsonSuccess(SuccessMessage.UPDATE_SUCCESS.getSucInfo(), resultDTO.getData(), response);
			} else {
				this.sendJsonError(resultDTO.getErrorMessage(), response);
			}
		}catch (BusinessException e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(e.getError(), response);
        }catch (Exception e) {
		    LogUtil.error("上传图片异常", e);
			this.sendJsonError(ErrorMessages.ATTACHMENT_UPLOAD_ERROR, response);
		}
	}
	/**
	 * 上传图片 需要压缩（多个）
	 * @param request
	 * @param response
	 * @param height
	 * @param width
	 */
	@RequestMapping("/uploadImageFiles.jpeg")
    public void uploadImageFiles(HttpServletRequest request, HttpServletResponse response, Integer height,
            Integer width) {
        try {
            if(height ==0){
                height =null;
            }
            ResultDTO<List<RemoteFileInfo>> resultDTO = remoteFileService.saveUploadImageFiles(request, height, width);
            if (resultDTO.isSuccess()) {
                this.sendJsonSuccess(SuccessMessage.UPDATE_SUCCESS.getSucInfo(), resultDTO.getData(), response);
            } else {
                this.sendJsonError(resultDTO.getErrorMessage(), response);
            }
        }catch (BusinessException e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(e.getError(), response);
        }catch (Exception e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(ErrorMessages.ATTACHMENT_UPLOAD_ERROR, response);
        }
    }
	@RequestMapping("/baiduUeditorUploadImage.jpeg")
	public void baiduUeditorUploadImage(HttpServletRequest request, HttpServletResponse response, Integer height,
			Integer width) {

		try {
			ResultDTO<RemoteFileInfo> resultDTO = remoteFileService.saveUploadImageFile(request, height, width,false);
			if (resultDTO.isSuccess()) {
				RemoteFileInfo remoteFileInfo = resultDTO.getData();
				String picName = remoteFileInfo.getFileName();
				Map<String, String> ueditorMap = new HashMap<String, String>();
				ueditorMap.put("name", picName);
				ueditorMap.put("originalName", picName);
				ueditorMap.put("url", remoteFileInfo.getCompressFilePath());
				ueditorMap.put("state", "SUCCESS");
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().print(JSON.toJSONString(ueditorMap));
				response.getWriter().flush();
				response.getWriter().close();
			} else {
				this.sendJsonError(resultDTO.getErrorMessage(), response);
			}
		} catch (BusinessException e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(e.getError(), response);
        }catch (Exception e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(ErrorMessages.ATTACHMENT_UPLOAD_ERROR, response);
        }

	}

	/**
	 * 上传附件
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/upLoadFile.jpeg")
	public void upLoadFile(HttpServletRequest request, HttpServletResponse response) {
		try {
			ResultDTO<RemoteFileInfo> resultDTO = remoteFileService.saveUploadFile(request);
			if (resultDTO.isSuccess()) {
				this.sendJsonSuccess(SuccessMessage.UPDATE_SUCCESS.getSucInfo(), resultDTO.getData(), response);
			} else {
				this.sendJsonError(resultDTO.getErrorMessage(), response);
			}
		} catch (BusinessException e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(e.getError(), response);
        }catch (Exception e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(ErrorMessages.ATTACHMENT_UPLOAD_ERROR, response);
        }
	}

	@RequestMapping("/upLoadFiles.jpeg")
	public void upLoadFiles(HttpServletRequest request, HttpServletResponse response) {
		try {
			ResultDTO<List<RemoteFileInfo>> resultDTO = remoteFileService.saveUploadFiles(request);
			if (resultDTO.isSuccess()) {
				this.sendJsonSuccess(SuccessMessage.UPDATE_SUCCESS.getSucInfo(), resultDTO.getData(), response);
			} else {
				this.sendJsonError(resultDTO.getErrorMessage(), response);
			}
		} catch (BusinessException e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(e.getError(), response);
        }catch (Exception e) {
            LogUtil.error("上传图片异常", e);
            this.sendJsonError(ErrorMessages.ATTACHMENT_UPLOAD_ERROR, response);
        }
	}

	@RequestMapping(value = "downFileById.do")
	public void downFileById(HttpServletResponse response, String id) {
		OutputStream os = null;
		InputStream inputStream = null;
		try {
			ResultDTO<RemoteFileInfo> resultDO = remoteFileService.selectByPrimaryKey(id);
			if (resultDO.isSuccess()) {
				RemoteFileInfo obj = resultDO.getData();
				String urlpath = obj.getSourceFilePath();
				String fileName = urlpath.substring(urlpath.lastIndexOf("/") + 1);
				response.setContentType("application/octet-stream;charset=UTF-8");
				response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
				URL url = new URL(urlpath);
				HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
				inputStream = httpUrl.getInputStream();
				os = response.getOutputStream();
				byte[] b = new byte[2048];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				os.flush();
			}
		} catch (Exception e) {
		    LogUtil.error("下载异常", e);
			this.sendJsonError(ErrorMessages.ATTACHMENT_DOWNLOAD_ERROR, response);
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
